package com.jayden.scalevideoplayer.videoplayer;

import android.content.res.AssetFileDescriptor;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.os.Build;
import android.view.Surface;

import java.io.IOException;

/**
 * 实现了基于MediaPlayer的播放器
 * <p>
 * Created by LiuYanBing
 */
public class MediaPlayerControl extends VideoControl implements MediaPlayer.OnPreparedListener {
    private static final String TAG = "MediaPlayerControl";
    private MediaPlayer mMediaPlayer;
    private Surface mSurface;

    public MediaPlayerControl(VideoPlayerView view) {
        super(view);
    }

    @Override
    public void initPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnPreparedListener(this);
        if (mSurface != null) {
            mMediaPlayer.setSurface(mSurface);
        }
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface) {
        mSurface = new Surface(surface);
        if (mMediaPlayer != null) {
            mMediaPlayer.setSurface(mSurface);
        }
    }

    @Override
    public void onSurfaceTextureDestroyed(SurfaceTexture surface) {
        if (mSurface != null) {
            mSurface.release();
            mSurface = null;
        }
    }

    /**
     * 设置播放源及预加载
     */
    public void setDataSource(Object source) {
        if (source == null) {
            return;
        }
        try {
            if (source instanceof AssetFileDescriptor) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    mMediaPlayer.setDataSource((AssetFileDescriptor) source);
                }
            } else if (source instanceof String) {
                mMediaPlayer.setDataSource((String) source);
            } else {
                return;
            }
            mMediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }
}
